package com.anyanyway.log;

import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Enumeration;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.io.file.FileSystemRegistry;

/**
 * An implemented Logger appender that write the log to a file if the real
 * device suppose file accessing.
 * 
 * @author anyanyway@gmail.com
 * 
 */
public class FileLogger implements Logger {

	private static FileConnection fc = null;
	private static DataOutputStream ous = null;
	private static final String FILE_URL = "file:///";

	private static final String FOLDER = "log";
	private static final String FILE_NAME = "log";

	public final byte PLATFORM_NOKIA_S40 = 0;
	public final byte PLATFORM_NOKIA_S60 = 1;
	public final byte PLATFORM_SONY_ERICSSON = 2;

	public byte platform = PLATFORM_SONY_ERICSSON;
	private static String root;

	public FileLogger() {
		createFile();
	}

	/**
	 * @param platform indicates the platform on witch the application runs.
	 * The three static constants in this class represents the three supported platform :
	 * <code>PLATFORM_NOKIA_S40</code>,<code>PLATFORM_NOKIA_S60</code> and <code>PLATFORM_SONY_ERICSSON</code>.
	 */
	public FileLogger(final byte platform) {
		this.platform = platform;
		createFile();
	}

	private void initRoot() {
		switch (platform) {
		case PLATFORM_NOKIA_S40:
			root = "file:///C:/predefgallery/predefmusic";
			break;
		case PLATFORM_NOKIA_S60:
			root = "file:///c:/pictures/";
			break;
		case PLATFORM_SONY_ERICSSON:
			root = "file:///c:/pictures/";
			break;

		default:
			break;
		}
	}

	private void createFile() {
		initRoot();
		if (ous != null)
			return;
		String version = System
				.getProperty("microedition.io.file.FileConnection.version");
		if (version != null) {
			if (root == null) {
				root = FILE_URL + getDefaultRoot();
			}
			try {
				fc = (FileConnection) Connector.open(root + FOLDER + "/",
						Connector.READ_WRITE);
				if (!fc.exists()) {
					fc.mkdir();
				}
				fc.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}

			try {
				fc = (FileConnection) Connector.open(root + FOLDER + "/"
						+ FILE_NAME + ".txt", Connector.READ_WRITE);
				if (fc.exists()) {
					fc.delete();
				}
				fc.create();
				ous = fc.openDataOutputStream();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}

	private String getDefaultRoot() {
		String sRoot = null;
		Enumeration enumDrive = FileSystemRegistry.listRoots();
		while (enumDrive.hasMoreElements())
			sRoot = (String) enumDrive.nextElement();
		return sRoot;
	}

	public void println(String str) {
		if (ous == null)
			return;
		try {
			ous.write(str.getBytes());
			ous.flush();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

}
